package com.learn.spring.async.config;

import lombok.RequiredArgsConstructor;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 配置自定义的TaskExecutor线程池
 *
 * @author: MI
 * @email 448341911@qq.com
 * @createDate: 2023/10/21 11:30
 * @updateUser: MI
 * @updateDate: 2023/10/21 11:30
 * @updateRemark: 修改内容
 * @version: v1.0
 */
@RequiredArgsConstructor
@Configuration
@EnableConfigurationProperties(ThreadPoolProperties.class)
public class ThreadPoolTaskConfig {

    private final ThreadPoolProperties properties;

    @Bean(name = "asyncExecutor")
    public ThreadPoolTaskExecutor taskExecutor() {
        // spring封装的一个线程池
        ThreadPoolTaskExecutor threadPool = new ThreadPoolTaskExecutor();
        // 随便写一些配置
        threadPool.setCorePoolSize(properties.getCorePoolSize());
        threadPool.setMaxPoolSize(properties.getMaxPoolSize());
        threadPool.setQueueCapacity(properties.getQueueCapacity());
        threadPool.setKeepAliveSeconds(properties.getKeepAliveSeconds());
        threadPool.setThreadNamePrefix(properties.getThreadNamePrefix());
        // 拒绝策略
        threadPool.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPool;
    }

}

